<!--
 * @copyright 2025 银杏ERP
 * @author 银杏ERP
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
-->

<template>
    <el-card shadow="hover" class="trend-chart-card">
        <template #header>
            <div class="card-header">
                <div class="title-with-icon">
                    <Icon name="fa fa-line-chart" class="title-icon" />
                    <span>{{ t('业务趋势') }}</span>
                </div>
                <div class="header-actions">
                    <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                        <el-radio-button label="week">{{ t('近7天') }}</el-radio-button>
                        <el-radio-button label="month">{{ t('近30天') }}</el-radio-button>
                    </el-radio-group>
                </div>
            </div>
        </template>
        <div class="chart-filter">
            <div class="chart-legend">
                <div class="legend-item">
                    <div class="legend-color inbound-color"></div>
                    <span>{{ t('入库量') }}</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color outbound-color"></div>
                    <span>{{ t('出库量') }}</span>
                </div>
                <div class="legend-item">
                    <div class="legend-color transfer-color"></div>
                    <span>{{ t('调拨量') }}</span>
                </div>
            </div>
            <div class="data-summary">
                <div class="summary-item">
                    <div class="summary-label">{{ t('总入库') }}</div>
                    <div class="summary-value inbound">{{ totalInbound }}</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">{{ t('总出库') }}</div>
                    <div class="summary-value outbound">{{ totalOutbound }}</div>
                </div>
                <div class="summary-item">
                    <div class="summary-label">{{ t('总调拨') }}</div>
                    <div class="summary-value transfer">{{ totalTransfer }}</div>
                </div>
            </div>
        </div>
        <div v-loading="chartLoading" class="chart-container">
            <div ref="chartRef" class="echarts-container"></div>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import * as echarts from 'echarts/core'
import { LineChart } from 'echarts/charts'
import { 
    TitleComponent, 
    TooltipComponent, 
    GridComponent, 
    LegendComponent,
    ToolboxComponent,
    DataZoomComponent 
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import dayjs from 'dayjs'
import Icon from '/@/components/icon/index.vue'

// 注册 ECharts 必须的组件
echarts.use([
    TitleComponent, 
    TooltipComponent, 
    GridComponent, 
    LegendComponent,
    ToolboxComponent,
    DataZoomComponent,
    LineChart,
    CanvasRenderer
])

const { t } = useI18n()

const chartRef = ref<HTMLElement | null>(null)
const chartLoading = ref(true)
let chart: echarts.ECharts | null = null
const timeRange = ref('week')
const totalInbound = ref('56,428')
const totalOutbound = ref('43,680')
const totalTransfer = ref('12,378')

// 生成日期标签
const generateDateLabels = (days: number) => {
    const labels = []
    for (let i = days - 1; i >= 0; i--) {
        labels.push(dayjs().subtract(i, 'day').format('MM-DD'))
    }
    return labels
}

// 生成测试数据
const generateWeekData = () => {
    return {
        dateLabels: generateDateLabels(7),
        inboundData: [1850, 2210, 1830, 2100, 2560, 1680, 1950],
        outboundData: [1560, 1810, 1450, 1680, 2120, 1340, 1880],
        transferData: [380, 520, 460, 570, 610, 430, 510]
    }
}

const generateMonthData = () => {
    const dateLabels = generateDateLabels(30)
    const inboundData = []
    const outboundData = []
    const transferData = []
    
    for (let i = 0; i < 30; i++) {
        // 生成随机数据，模拟波动趋势
        inboundData.push(Math.floor(Math.random() * 1000) + 1500)
        outboundData.push(Math.floor(Math.random() * 800) + 1200)
        transferData.push(Math.floor(Math.random() * 400) + 300)
    }
    
    return { dateLabels, inboundData, outboundData, transferData }
}

// 初始化并渲染趋势图
const initChart = () => {
    if (!chartRef.value) return
    
    chartLoading.value = true
    
    // 销毁之前的图表实例
    if (chart) {
        chart.dispose()
    }
    
    // 获取数据
    const data = timeRange.value === 'week' ? generateWeekData() : generateMonthData()
    
    chart = echarts.init(chartRef.value)
    
    const option = {
        tooltip: {
            trigger: 'axis',
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            borderColor: '#eee',
            borderWidth: 1,
            padding: [10, 15],
            textStyle: {
                color: '#333'
            },
            formatter: function(params: any) {
                let result = `<div style="font-weight: bold; margin-bottom: 5px;">${params[0].axisValue}</div>`
                params.forEach((item: any) => {
                    let color = '#666'
                    if (item.seriesName === t('入库量')) color = '#1E88E5'
                    else if (item.seriesName === t('出库量')) color = '#26A69A'
                    else if (item.seriesName === t('调拨量')) color = '#8E24AA'
                    
                    result += `<div style="display: flex; justify-content: space-between; align-items: center; margin-top: 3px;">
                        <span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: ${color}; margin-right: 5px;"></span>
                        <span style="margin-right: 15px;">${item.seriesName}: </span>
                        <span style="font-weight: bold; color: ${color};">${item.value}</span>
                    </div>`
                })
                return result
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            top: '8%',
            containLabel: true
        },
        dataZoom: [{
            type: 'inside',
            start: timeRange.value === 'week' ? 0 : 70,
            end: 100
        }, {
            type: 'slider',
            show: timeRange.value === 'month',
            start: timeRange.value === 'week' ? 0 : 70,
            end: 100,
            height: 20,
            bottom: '2%'
        }],
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: data.dateLabels,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisLabel: {
                color: '#666',
                formatter: function(value: string) {
                    return value
                }
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#666'
            },
            splitLine: {
                lineStyle: {
                    color: '#eee',
                    type: 'dashed'
                }
            }
        },
        series: [
            {
                name: t('入库量'),
                type: 'line',
                smooth: true,
                data: data.inboundData,
                lineStyle: {
                    width: 3,
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: '#1E88E5' },
                            { offset: 1, color: '#42A5F5' }
                        ]
                    }
                },
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                    color: '#1E88E5',
                    borderColor: '#fff',
                    borderWidth: 2
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(30, 136, 229, 0.3)' },
                            { offset: 1, color: 'rgba(30, 136, 229, 0.05)' }
                        ]
                    }
                }
            },
            {
                name: t('出库量'),
                type: 'line',
                smooth: true,
                data: data.outboundData,
                lineStyle: {
                    width: 3,
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: '#26A69A' },
                            { offset: 1, color: '#4DB6AC' }
                        ]
                    }
                },
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                    color: '#26A69A',
                    borderColor: '#fff',
                    borderWidth: 2
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(38, 166, 154, 0.3)' },
                            { offset: 1, color: 'rgba(38, 166, 154, 0.05)' }
                        ]
                    }
                }
            },
            {
                name: t('调拨量'),
                type: 'line',
                smooth: true,
                data: data.transferData,
                lineStyle: {
                    width: 3,
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: '#8E24AA' },
                            { offset: 1, color: '#AB47BC' }
                        ]
                    }
                },
                symbol: 'circle',
                symbolSize: 6,
                itemStyle: {
                    color: '#8E24AA',
                    borderColor: '#fff',
                    borderWidth: 2
                },
                areaStyle: {
                    color: {
                        type: 'linear',
                        x: 0,
                        y: 0,
                        x2: 0,
                        y2: 1,
                        colorStops: [
                            { offset: 0, color: 'rgba(142, 36, 170, 0.3)' },
                            { offset: 1, color: 'rgba(142, 36, 170, 0.05)' }
                        ]
                    }
                }
            }
        ]
    }
    
    chart.setOption(option)
    chartLoading.value = false
}

// 时间范围切换
const handleTimeRangeChange = () => {
    // 更新汇总数据
    if (timeRange.value === 'week') {
        totalInbound.value = '56,428'
        totalOutbound.value = '43,680'
        totalTransfer.value = '12,378'
    } else {
        totalInbound.value = '247,256'
        totalOutbound.value = '192,540'
        totalTransfer.value = '51,790'
    }
    
    // 重新渲染图表
    initChart()
}

// 窗口调整时重绘图表
const handleResize = () => {
    chart?.resize()
}

// 监听窗口大小变化
window.addEventListener('resize', handleResize)

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    chart?.dispose()
})

// 组件挂载完成后初始化
onMounted(() => {
    nextTick(() => {
        initChart()
    })
})
</script>

<style scoped lang="scss">
.trend-chart-card {
    height: 420px;
    margin-bottom: 20px;
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .title-with-icon {
            display: flex;
            align-items: center;
            
            .title-icon {
                color: #409EFF;
                margin-right: 8px;
                font-size: 16px;
            }
        }
        
        .header-actions {
            display: flex;
            align-items: center;
        }
    }
    
    .chart-filter {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        
        .chart-legend {
            display: flex;
            align-items: center;
            
            .legend-item {
                display: flex;
                align-items: center;
                margin-right: 16px;
                
                .legend-color {
                    width: 12px;
                    height: 12px;
                    border-radius: 50%;
                    margin-right: 8px;
                    
                    &.inbound-color {
                        background-color: #1E88E5;
                    }
                    
                    &.outbound-color {
                        background-color: #26A69A;
                    }
                    
                    &.transfer-color {
                        background-color: #8E24AA;
                    }
                }
            }
        }
        
        .data-summary {
            display: flex;
            align-items: center;
            
            .summary-item {
                margin-left: 20px;
                text-align: center;
                
                .summary-label {
                    font-size: 12px;
                    color: #909399;
                    margin-bottom: 2px;
                }
                
                .summary-value {
                    font-weight: bold;
                    font-size: 16px;
                    
                    &.inbound {
                        color: #1E88E5;
                    }
                    
                    &.outbound {
                        color: #26A69A;
                    }
                    
                    &.transfer {
                        color: #8E24AA;
                    }
                }
            }
        }
    }
    
    .chart-container {
        height: 300px;
        
        .echarts-container {
            width: 100%;
            height: 100%;
        }
    }
}

@media screen and (max-width: 768px) {
    .trend-chart-card {
        height: auto;
        
        .chart-filter {
            flex-direction: column;
            align-items: flex-start;
            
            .data-summary {
                margin-top: 10px;
                width: 100%;
                justify-content: space-between;
                
                .summary-item {
                    margin-left: 0;
                }
            }
        }
        
        .chart-container {
            height: 250px;
        }
    }
}
</style> 